package me.goldze.mvvmhabit.http;

import com.google.gson.JsonParseException;
import com.google.gson.stream.MalformedJsonException;

import android.net.ParseException;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;

import me.goldze.mvvmhabit.utils.ToastUtils;
import retrofit2.HttpException;


/**
 * Created by goldze on 2017/5/11.
 */
public class ExceptionHandle {

    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int SERVICE_UNAVAILABLE = 503;

    public static ResponseThrowable handleException(Throwable e){
//        Log.e("TAG","===========handleException==========");
        ResponseThrowable ex;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
//            ex = new ResponseThrowable(e, ERROR.HTTP_ERROR);
//            Log.e("TAG","===========handleException=======httpException.code()==="+httpException.code());
            ex = new ResponseThrowable(e, httpException.code());
//            switch (httpException.code()) {
//                case UNAUTHORIZED:
//                    ex.message = "操作未授权";
//                    break;
//                case FORBIDDEN:
//                    ex.message = "请求被拒绝";
//                    break;
//                case NOT_FOUND:
//                    ex.message = "资源不存在";
//                    break;
//                case REQUEST_TIMEOUT:
//                    ex.message = "服务器执行超时";
//                    break;
//                case INTERNAL_SERVER_ERROR:
//                    ex.message = "服务器内部错误";
//                    break;
//                case SERVICE_UNAVAILABLE:
//                    ex.message = "服务器不可用";
//                    break;
//                default:
////                    ex.message = "网络错误";
//                    ex.message = httpException.message();
//                    break;
//            }
            if(httpException.code() == 429)
            {
                ToastUtils.showShort("操作太频繁了");
            }

            ex.message = httpException.message();
            try {
//                Log.e("TAG",(httpException.response().errorBody().string()) + "===========response=======");
                String msg = "您已经被禁";
                if(null != httpException.response() && null != httpException.response().errorBody())
                {
                    ex.errorBody = httpException.response().errorBody().string();
                    msg = getShowmessage(ex.errorBody);
                }
                if(httpException.code() == 403)
                {
                    ToastUtils.showShort(msg);
                }

            } catch (Exception ioException) {
                ioException.printStackTrace();
            }
            return ex;
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException || e instanceof MalformedJsonException) {
            ex = new ResponseThrowable(e, ERROR.PARSE_ERROR);
            ex.message = "解析错误";
            return ex;
        } else if (e instanceof ConnectException) {
            ex = new ResponseThrowable(e, ERROR.NETWORD_ERROR);
            ex.message = "连接失败";
            return ex;
        } else if (e instanceof javax.net.ssl.SSLException) {
            ex = new ResponseThrowable(e, ERROR.SSL_ERROR);
            ex.message = "证书验证失败";
            return ex;
        } else if (e instanceof ConnectTimeoutException) {
            ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
            ex.message = "连接超时";
            return ex;
        } else if (e instanceof java.net.SocketTimeoutException) {
            ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
            ex.message = "连接超时";
            return ex;
        } else if (e instanceof java.net.UnknownHostException) {
            ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
            ex.message = "主机地址未知";
            return ex;
        }
        else if(e instanceof EOFException)
        {
            EOFException httpException = (EOFException) e;
            ex = new ResponseThrowable(e, httpException.hashCode());
            ex.message = "主机地址未知";
            return ex;
        }
        else {
            ex = new ResponseThrowable(e, ERROR.UNKNOWN);
            ex.message = "未知错误";
            return ex;
        }
    }

    public static String getShowmessage(String body) {
        String message = "";
        try {
//            Log.e("TAG","===========getShowmessage=========="+body);
            if (!TextUtils.isEmpty(body)) {
                if(body.startsWith("<!DOCTYPE html"))
                {
                    message = "操作失败";
//                    Log.e("TAG","===========getShowmessage=====失败====="+body);
                }
                else
                {
                    JSONObject jsonObject = new JSONObject(body);
                    if (jsonObject.has("err_msg")) {
                        message = jsonObject.getString("err_msg");
                    }
                    else if(jsonObject.has("errors"))
                    {
                        message = jsonObject.getString("errors");
                        JSONObject jsonObjecterrors = jsonObject.optJSONObject("errors");
//                    Log.e("TAG","===========getShowmessage===0000======="+jsonObjecterrors.names());
                        if(jsonObjecterrors != null && jsonObjecterrors.names() !=null && jsonObjecterrors.names().length() > 0)
                        {
                            String key = (String) jsonObjecterrors.names().get(0);
//                        Log.e("TAG","===========getShowmessage===1111======="+key);
                            JSONArray messages = jsonObjecterrors.optJSONArray(key);
//                        Log.e("TAG","===========getShowmessage===2222======="+(messages!=null));
                            if(messages!=null && messages.length() > 0)
                            {
                                message = messages.getString(0);
                            }
                        }
                    }
                    else if(jsonObject.has("message"))
                    {
                        message = jsonObject.getString("message");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (TextUtils.isEmpty(message)) {
                message = "您已经被禁";
            }
        }
        return message;
    }
    /**
     * 约定异常 这个具体规则需要与服务端或者领导商讨定义
     */
    class ERROR {
        /**
         * 未知错误
         */
        public static final int UNKNOWN = 1000;
        /**
         * 解析错误
         */
        public static final int PARSE_ERROR = 1001;
        /**
         * 网络错误
         */
        public static final int NETWORD_ERROR = 1002;
        /**
         * 协议出错
         */
        public static final int HTTP_ERROR = 1003;

        /**
         * 证书出错
         */
        public static final int SSL_ERROR = 1005;

        /**
         * 连接超时
         */
        public static final int TIMEOUT_ERROR = 1006;
    }

}

